<?php

namespace Hr\OnlineBundle\Controller;

use Hr\OnlineBundle\Controller\GenericController;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Hr\OnlineBundle\Entity\Position;
use Symfony\Component\HttpFoundation\Session\Session;


class PositionController extends GenericController
{
    public function searchAction()
    {
	
		parent::init();

        $em = $this->getDoctrine()->getManager();

		$maxPerPage = $this->container->getParameter('hr_online.max_positions_per_page', 10);

		$qb = $em->getRepository('HrOnlineBundle:Position')->getSelectLatestQueryBuilder();
		
		$paginator = $this->getDoctrinePaginator( $qb, $maxPerPage);
		
		$totalResults = count($paginator);

		$numPages = ceil($totalResults/$maxPerPage);

		$page = $this->getRequest()->query->get("page", 1) ;
		
        return $this->render('HrOnlineBundle:Position:search.html.twig',  array(
				'paginator' => $paginator,
				'numPages' =>  $numPages,
				'page' => $page
		));
	}


    /**
     * Show a position entry
     */
    public function showAction($id, $slug, $_locale=null)
    {
		parent::init($_locale);

        $em = $this->getDoctrine()->getManager();

        $position = $em->getRepository('HrOnlineBundle:Position')->find($id);

		$user = $this->get('security.context')->getToken()->getUser();

		$application = $em->getRepository('HrOnlineBundle:Application')->findOneBy(array('user'=>$user, 'position'=>$position));
		
		$apply = true;
		if (isset($application)) {
			$msg = "You have already applied for this position.";
			$this->get('session')->getFlashBag()->add('success', $msg);
			$apply = false;
		}

        if (!$position) {
            throw $this->createNotFoundException('Unable to find position.');
        }
				
		return $this->render('HrOnlineBundle:Position:show.html.twig', array(
			'position'      => $position,
			'apply'      => $apply
		));
    }






    public function rememberAction(Request $request)
    {

		$positionId = $request->query->get('id');
		
		$em = $this->getDoctrine()->getManager();
		$position = $em->getRepository('HrOnlineBundle:Position')->findOneBy(array('id'=>$positionId));
		
		if (!isset($position)) {

			$msg = "Position not found.";
			$this->get('session')->getFlashBag()->add('error', $msg);
		
		} else {

			$session = $this->getRequest()->getSession();
			if (!isset($session)) {
				$session = new Session();
				try {
					$session->start();
				} catch (\RuntimeException $e) {
					// already started
				}
			}

			if (isset($session)) {
				$session->set('last_marked_position', $positionId);
				$msg =  'Position put to wishlist. Please login to apply.';
				$this->get('session')->getFlashBag()->add('success', $msg);
			} else {
				$msg =  'Unable to use session';
				$this->get('session')->getFlashBag()->add('error', $msg);
			}

		}

        return $this->render('HrOnlineBundle:Default:_flashes.html.twig');
    }




}